<?php

namespace App\Http\Controllers\Admin;

use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityWorksType;
use App\Models\CompetiteActivityWorks;
use App\Models\Manage;
use App\Validate\CompetiteActivityWorksTypeValidate;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品类型
 */
class CompetiteActivityWorksTypeController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new CompetiteActivityWorksType();
        $this->validate = new CompetiteActivityWorksTypeValidate();
    }


    /**
     * @param con_id int 活动大赛id
     * 类型(用于下拉框选择)
     */
    public function filterList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('filter_lists')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $res = $this->model->select(['id', 'type_name', 'limit_num', 'letter', 'node'])
            ->where('con_id', $this->request->con_id)
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->get();

        if ($res->isEmpty()) {
            return $this->returnApi(203, "暂无数据");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }


    /**
     * 列表
     * @param con_id int 活动大赛id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('lists')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $con_id = $this->request->con_id;

        $condition[] = ['is_del', '=', 1];

        if ($keywords) {
            $condition[] = ['type_name', 'like', "%$keywords%"];
        }
        if ($con_id) {
            $condition[] = ['con_id', '=', $con_id];
        }
        $res = $this->model->select('id', 'con_id', 'type_name', 'limit_num', 'letter', 'node', 'score_manage_id', 'create_time')
            ->where($condition)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        if ($res['data']) {
            $res = $this->disPageData($res);
            //增加序号
            $competiteActivity = new CompetiteActivity();
            foreach ($res['data'] as $key => $val) {
                if ($val['node']) {
                    $res['data'][$key]['node_name'] = $competiteActivity->getNodeName($val['node']);
                } else {
                    $res['data'][$key]['node_name'] = '';
                }
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
                //  $res['data'][$key]['score_manage_name'] = Manage::getManageNameByManageId($val['score_manage_id']);

                //新增打分人是多个人
                $score_manage_id = explode(',', $val['score_manage_id']);
                $score_manage_data = '';
                foreach ($score_manage_id as $k => $v) {
                    $score_manage_data .= '、' . Manage::getManageNameByManageId($v);
                }
                $res['data'][$key]['score_manage_name'] = trim($score_manage_data, '、');
            }

            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 详情
     * @param id int 类型id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->select('id', 'con_id', 'type_name', 'limit_num', 'letter', 'node', 'score_manage_id', 'create_time')->find($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $competiteActivity = new CompetiteActivity();
        $res['node_name'] = $competiteActivity->getNodeName($res['node']);
        //之前的数据
        $res['score_manage_name'] = is_int($res['score_manage_id']) ? Manage::getManageNameByManageId($res['score_manage_id']) : null;

        //新增打分人是多个人
        $score_manage_id = explode(',', $res['score_manage_id']);
        $res['score_manage_data'] = [];
        foreach ($score_manage_id as $key => $val) {
            $res['score_manage_data'][$key]['score_manage_id'] = $val;
            $res['score_manage_data'][$key]['score_manage_name'] = Manage::getManageNameByManageId($val);
        }
        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param con_id int 大赛id
     * @param type_name string 类型名称
     * @param limit_num string 限制该分类作品上传最大数量  0为不限
     * @param letter string 编号首字母
     * @param node string 上传文件类型，连接  1.图片(默认)  2.文字  3.音频  4.视频  多个逗号链接
     * @param score_manage_id string 打分管理员id，只有当前大赛可以打分才存在  多个打分人逗号拼接
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        // $node = $this->request->node;
        // $nodes = explode(',', $node);
        // if(in_array(3 , $nodes) && in_array(4 , $nodes)){
        //     return $this->returnApi(201, "视频和音频不能同时存在");
        // }

        $competiteActivityInfo = CompetiteActivity::where('id', $this->request->con_id)->where('is_del', 1)->first();
        if (empty($competiteActivityInfo)) {
            return $this->returnApi(201, "大赛活动不存在");
        }
        if ($competiteActivityInfo->appraise_way == 2 && $this->request->score_manage_id) {
            return $this->returnApi(201, "此大赛活动不支持专家评审");
        }
        if ($competiteActivityInfo->appraise_way != 2 && empty($this->request->score_manage_id)) {
            return $this->returnApi(201, "请选择专家评审管理员");
        }

        $findWhere[] = ['con_id', '=', $this->request->con_id];
        $is_exists = $this->model->nameIsExists($this->request->type_name, 'type_name', null, 1, $findWhere);

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }
        $this->request->merge(['letter' => strtoupper($this->request->letter)]);
        $res = $this->model->add($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 修改
     * @param id int 类型id
     * @param con_id int 大赛id
     * @param type_name string 类型名称
     * @param limit_num string 限制该分类作品上传最大数量  0为不限
     * @param letter string 编号首字母
     * @param node string 上传文件类型，连接  1.图片(默认)  2.文字  3.音频  4.视频  多个逗号链接
     * @param score_manage_id string 打分管理员id，只有当前大赛可以打分才存在
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        // $node = $this->request->node;
        // $nodes = explode(',', $node);
        // if(in_array(3 , $nodes) && in_array(4 , $nodes)){
        //     return $this->returnApi(201, "视频和音频不能同时存在");
        // }
        $competiteActivityInfo = CompetiteActivity::where('id', $this->request->con_id)->where('is_del', 1)->first();
        if (empty($competiteActivityInfo)) {
            return $this->returnApi(201, "大赛活动不存在");
        }
        if ($competiteActivityInfo->appraise_way == 2 && $this->request->score_manage_id) {
            return $this->returnApi(201, "此大赛活动不支持专家评审");
        }
        if ($competiteActivityInfo->appraise_way != 2 && empty($this->request->score_manage_id)) {
            return $this->returnApi(201, "请选择专家评审管理员");
        }

        $findWhere[] = ['con_id', '=', $this->request->con_id];
        $is_exists = $this->model->nameIsExists($this->request->type_name, 'type_name',  $this->request->id, 1, $findWhere);

        if ($is_exists) {
            return $this->returnApi(202, "此名称已存在");
        }

        $res = $this->model->where('id', $this->request->id)->where('is_del', 1)->first();
        if (empty($res)) {
            return $this->returnApi(202, "参数错误");
        }
        $competiteAcivityWorksModel = new CompetiteActivityWorks();
        if ($res['score_manage_id'] != $this->request->score_manage_id) {
            //判断是否有作品已经审核通过，存在则不能修改
            $is_exists_works_status = $competiteAcivityWorksModel->where('con_id', $this->request->con_id)->where('type_id', $this->request->id)->where('status', 1)->first();
            if ($is_exists_works_status) {
                return $this->returnApi(202, "当前类型下已有作品已审核通过，不能修改打分人");
            }
        }
        DB::beginTransaction();
        try {

            $this->request->merge(['letter' => strtoupper($this->request->letter)]);
            $this->model->change($this->request->all());

            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否有作品
        $isHaveProduction = CompetiteActivityWorks::where('type_id', $this->request->id)->where('status', '<>', 5)->first();
        if ($isHaveProduction) {
            return $this->returnApi(202, "此类型已存在作品，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }
}
